<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 整个过程就是将所有的渲染操作封装到一个构造函数问题，解决了上一次编写中代码没有整合的问题 -->
    <div id="root">
        <p>{{name}}</p>
        <p>{{message}}</p>
    </div>
    <script>
         let r = /\{\{(.+?)\}\}/g
         function JGVue(options){
            this._data = options.data
            this._el = options.el

            //准备模板和数据
            this._temNode = document.querySelector(this._el)
            this._parent = this._temNode.parentNode

            //渲染页面
            this.render()
         }
         //通过这个函数解决了首次编写代码时不能实现对层级属性查找的问题
         function getValueByPath(obj,path){
             let paths = path.split('.')
             let res = obj
             let prop
             while(prop = paths.shift()){
                 res = res[prop]
             }
             return res
         }
         function compiler(template,data){
             let childNodes = template.childNodes
             for(let i = 0; i < childNodes.length; i++){
                 let type = childNodes[i].nodeType
                 if(type === 3){
                    let txt = childNodes[i].nodeValue
                    txt = txt.replace(r,function(a,b){
                        let path = b.trim()
                        let value = getValueByPath(data,path)
                        return value
                    })
                    childNodes[i].nodeValue = txt
                 }else if(type === 1){
                     compiler(childNodes[i],data)
                 }
             }
         }
         //render函数，将的到的Html渲染到页面
         JGVue.prototype.render = function(){
            this.compiler()
         }

         //编译，将数据与模板整合到一起，的到真正的DOM元素
         JGVue.prototype.compiler = function(){
            let realHtml = this._temNode.cloneNode(true)
            compiler(realHtml,this._data)
            this.update(realHtml)
         }

         //将Dom中的元素放到页面中
         JGVue.prototype.update = function(realHtml){
            this._parent.replaceChild(realHtml,document.querySelector('#root'))
         }

         let app = new JGVue({
             el:'#root',
             data:{
                 name:'张三',
                 message:'新消息'
             }
         })
    </script>
</body>
</html>